package com.project;

import org.apache.catalina.Context;
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import javax.servlet.Servlet;
import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;


public class MainServlet {
    private ApplicationContext springContext = new AnnotationConfigApplicationContext(MybatisConfig.class);

    public MainServlet() {
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(8088);
        tomcat.getConnector();
        Context context = tomcat.addContext("",null);
        try {
            List<Class> list = this.getClasses("com.project.servlet");
            for(Class c : list){
                if (c.isAnnotationPresent(ServletObj.class)){
                    ServletObj servletObj = (ServletObj) c.getAnnotation(ServletObj.class);
                    this.registerServlet(context,c,servletObj.url());
                }
            }
            tomcat.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void registerServlet(Context context, Class serviceClass, String urlPath) throws Exception {
        Wrapper servlet = Tomcat.addServlet(context,serviceClass.getSimpleName(),(Servlet) serviceClass.newInstance());
        servlet.setLoadOnStartup(1);
        servlet.addMapping(urlPath);
    }

    public static List<Class> getClasses(String packageName) {
        List<Class> classList = new ArrayList<>();
        //获取包的名字 并进行替换
        String packageDirName = packageName.replace('.', '/');
        try {
            URL url = Thread.currentThread().getContextClassLoader()
                    .getResources(packageDirName).nextElement();
            String filePath = URLDecoder.decode(url.getFile(),"utf-8");
            File dirFile = new File(filePath);
            String[] classFiles =  dirFile.list();
            for(String f : classFiles){
                if(f.endsWith(".class")) {
                    String fileName = f.substring(0,f.lastIndexOf(".class"));
                    Class c = Class.forName(packageName+"."+fileName);
                    classList.add(c);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return classList;
    }

    public static void main(String[] args) {
        new MainServlet();
    }
}
